<template>
  <div class="Accounting">
    <!-- 头部 -->
    <van-sticky>
      <div class="heard">
        <div class="left">
          <div class="choose_time" @click="chooseTime">
            <van-icon name="todo-list-o" color="#fff" size="25" />
            <span class="time_content"
              >{{ showDate[0] }}年{{ showDate[1] }}月</span
            >
            <van-icon name="arrow-down" />
          </div>
          <div class="choose_time" @click="handleExport">导出</div>
        </div>

        <div class="total">
          <div class="totalcount">
            <span class="totaltitle">总计：</span>
            <span class="number"
              >{{ statisticsData.sums ? statisticsData.sums : "0.00" }}元</span
            >
          </div>
          <div class="totalcount">
            <span class="totaltitle">支出：</span>
            <span class="number"
              >{{
                statisticsData.paySums ? statisticsData.paySums : "0.00"
              }}元</span
            >
          </div>
          <div class="totalcount">
            <span class="totaltitle">收入：</span>
            <span class="number"
              >{{
                statisticsData.incomeSums ? statisticsData.incomeSums : "0.00"
              }}元</span
            >
          </div>
        </div>
      </div>
    </van-sticky>

    <!-- 身体部分 -->
    <div class="body_list">
      <!-- 每一天的记录 -->
      <template v-if="acountList.length > 0">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="list_item" v-for="item in acountList" :key="item.id">
            <div class="item_heard">
              <span class="release_time">
                <van-icon name="clock-o" color="#3eb575" size="15" />
                <span class="time_content">{{
                  formatDate.formatDate(item.createdDate, "YYYY年MM月DD日 WW")
                }}</span>
              </span>
              <span class="income_detail">
                <span class="out">
                  <span class="out_content">支出</span>
                  <span class="out_money">{{ item.paySum }}</span>
                </span>
                <span class="in">
                  <span class="in_content">收入</span>
                  <span class="in_money">{{ item.incomeSum }}</span>
                </span>
              </span>
            </div>
            <div
              class="item_content"
              v-for="it in item.consumeList"
              :key="it.id"
            >
              <van-swipe-cell
                :before-close="beforeClose"
                :name="{
                  id: it.id,
                  acountType: it.acountType,
                  number: it.number,
                  acountType: it.acountType,
                  card_id: it.card_id,
                }"
              >
                <div class="name_count">
                  <span class="name">{{ getType(it.type) }}</span>
                  <!-- 消费的卡名 -->
                  <div class="card_name" v-if="it.card_id != null">
                    <span
                      class="card_name_content"
                      :style="{
                        border: `1px solid ${it.acount_card.card_color}`,
                      }"
                      >{{ it.acount_card.card_name }}</span
                    >
                  </div>
                  <span class="count" v-if="it.acountType == 1"
                    >- {{ it.number }}</span
                  >
                  <span class="count" v-else>+ {{ it.number }}</span>
                </div>
                <div class="time_remask">
                  <span class="time">{{
                    formatDate.formatDate(it.beginTime, "HH:MM")
                  }}</span>
                  <span>|</span>
                  <span class="remask">{{
                    it.remask == "" ? "无" : it.remask
                  }}</span>
                </div>
                <template #right>
                  <van-button square type="danger" text="删除" />
                </template>
              </van-swipe-cell>
            </div>
          </div>
        </van-list>
      </template>

      <!-- 空状态 -->
      <van-empty :image="emptyImg" description="您本月还没有计过账！" v-else />
      <LayoutIndex />
    </div>
    <van-floating-bubble
      axis="xy"
      icon="records-o"
      v-model:offset="offset"
      magnetic="x"
      @click="showAccounting"
    />
    <!-- 日期选择器 -->
    <van-popup
      v-model:show="show"
      position="bottom"
      :style="{ padding: '15px', height: '40%' }"
      round
    >
      <van-date-picker
        @confirm="onConfirm"
        @cancel="onCancel"
        v-model="currentDate"
        title="选择年月"
        :max-date="new Date()"
        :columns-type="['year', 'month']"
      />
    </van-popup>
    <!-- 记账 -->
    <van-popup
      v-model:show="showAccount"
      position="bottom"
      :style="{ padding: '15px', height: '95%' }"
      round
    >
      <AddAcountVue v-if="showAccount" @successAdd="successAdd" />
    </van-popup>
    <!-- 遮罩层 -->
    <van-overlay :show="loading2" @click="loading2 = false" z-index="10000">
      <div class="wrapper" @click.stop>
        <van-loading size="30px" vertical color="#0094ff"
          >加载中...</van-loading
        >
      </div>
    </van-overlay>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { showConfirmDialog } from "vant";
import empty from "@/assets/empty.png";
import { useFormatTime } from "@/stores/formatTime.js";
import {
  queryAcountList,
  getStatisticsApi,
  deleteAccountReq,
  exportExcel,
} from "@/api/index.js";
import AddAcountVue from "./AddAcount.vue";
import LayoutIndex from "./layout/Index.vue";
import { showToast } from "vant";
const formatDate = useFormatTime();
// 空状态图片
const emptyImg = ref(empty);
// 浮动气泡的位置
const offset = ref({ x: "9rem", y: 700 });
const loading2 = ref(false);
const show = ref(false);
// 展示的年月
const showDate = ref([]);
// 当前年月
const currentDate = ref([]);
// 计算当前年月
const computedDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  currentDate.value = [year, month];
  showDate.value = [year, month];
};
//确定选中
const onConfirm = ({ selectedValues }) => {
  show.value = false;
  console.log(selectedValues);
  showDate.value = selectedValues;
  page.value.pageNum = 1;
  acountList.value = [];
  getData();
  getStatistics();
};
// 取消选中
const onCancel = () => {
  show.value = false;
  // 重置时间
  currentDate.value = showDate.value;
};
const chooseTime = () => {
  console.log("选择时间");
  show.value = true;
};
// 记账逻辑开始
const showAccount = ref(false);
const showAccounting = () => {
  showAccount.value = true;
  console.log("添加");
};
// 添加成功后
const successAdd = () => {
  showAccount.value = false;
  acountList.value = [];
  page.value.pageNum = 1;
  getData();
  getStatistics();
};
// 获取数据的逻辑
const acountList = ref([]);
const page = ref({
  pageSize: 32,
  pageNum: 1,
  totalCount: 0,
});
// 获取类型
const getType = (index) => {
  const type = [
    "餐饮",
    "购物",
    "服饰",
    "交通",
    "房租",
    "水费",
    "电费",
    "工资",
    "返现",
    "其他",
  ];
  return type[index];
};
const getData = async () => {
  loading2.value = true;
  // 本地缓存获取用户id
  const userInfo = localStorage.getItem("userInfo");
  const uid = JSON.parse(userInfo).id;
  // 计算开始时间结束时间
  const _startTime = `${showDate.value[0]}-${showDate.value[1]}-1`;
  const startTime = new Date(_startTime).getTime();
  // 根据月份获取下个月的第一天0点0分
  const _endTime = new Date(showDate.value[0], showDate.value[1], 1);
  // 设置时间为0点0分

  _endTime.setHours(0, 0, 0, 0);
  _endTime.setTime(_endTime.getTime() - 1);

  const endTime = _endTime.getTime();
  const params = {
    uid,
    startTime,
    endTime,
    pageSize: page.value.pageSize,
    pageNum: page.value.pageNum,
  };
  console.log(params);
  // 发起请求
  const res = await queryAcountList(params);
  loading2.value = false;
  if (res.status !== 200) {
    showToast("获取数据失败，请刷新重试！");
    return;
  }
  // 数据处理 计算支出、收入的总和
  for (const iterator of res.data) {
    let paySum = iterator.consumeList.reduce((accumulator, currentValue) => {
      if (currentValue.acountType == 1) {
        // 支出
        return accumulator - 0 + (currentValue.number - 0);
      } else {
        return accumulator - 0;
      }
    }, 0);
    let incomeSum = iterator.consumeList.reduce((accumulator, currentValue) => {
      if (currentValue.acountType == 2) {
        // 支出
        return accumulator - 0 + (currentValue.number - 0);
      } else {
        return accumulator - 0;
      }
    }, 0);
    // 如果number不存在小数点或者存在小数点了小数位不够两位在后面添加0
    if (!/\./.test(paySum)) {
      // 如果字符串中不存在小数点，则在末尾添加两位小数
      paySum += ".00";
    } else if (/\.\d$/.test(paySum)) {
      // 如果字符串中存在小数点，但小数位数不够两位，则在末尾添加一位小数
      paySum += "0";
    } else if (!/\.\d{2}$/.test(paySum)) {
      console.log(paySum);
      paySum = paySum + "";
      // 如果小数位数超过两位，则截取前两位小数
      paySum = paySum.replace(/(\.\d{2})\d*/, "$1");
    }
    // 如果number不存在小数点或者存在小数点了小数位不够两位在后面添加0
    if (!/\./.test(incomeSum)) {
      // 如果字符串中不存在小数点，则在末尾添加两位小数
      incomeSum += ".00";
    } else if (/\.\d$/.test(incomeSum)) {
      // 如果字符串中存在小数点，但小数位数不够两位，则在末尾添加一位小数
      incomeSum += "0";
    } else if (!/\.\d{2}$/.test(incomeSum)) {
      incomeSum = incomeSum + "";
      // 如果小数位数超过两位，则截取前两位小数
      incomeSum = incomeSum.replace(/(\.\d{2})\d*/, "$1");
    }
    iterator.paySum = paySum;
    iterator.incomeSum = incomeSum;
  }
  console.log("来到这里");
  acountList.value = [...acountList.value, ...res.data];
  page.value.totalCount = res.page.totalCount;
};
// 统计数据
const statisticsData = ref({});
// 获取统计
const getStatistics = async () => {
  loading2.value = true;
  // 本地缓存获取用户id
  const userInfo = localStorage.getItem("userInfo");
  const uid = JSON.parse(userInfo).id;
  // 计算开始时间结束时间
  const _startTime = `${showDate.value[0]}-${showDate.value[1]}-1`;
  const startTime = new Date(_startTime).getTime();
  // 根据月份获取下个月的第一天0点0分
  const _endTime = new Date(showDate.value[0], showDate.value[1], 1);
  // 设置时间为0点0分
  _endTime.setHours(0, 0, 0, 0);
  _endTime.setTime(_endTime.getTime() - 1);
  const endTime = _endTime.getTime();
  const params = {
    uid,
    startTime,
    endTime,
  };
  const res = await getStatisticsApi(params);
  loading2.value = false;
  if (res.status !== 200) {
    showToast("获取数据失败，请刷新重试！");
    return;
  }
  statisticsData.value = res.data;
};
const loading = ref(false);
const finished = ref(false);
const onLoad = () => {
  // loading.value = true;
  console.log("dianyong");
  loading.value = false;
  page.value.pageNum += 1;
  getData();

  // 数据全部加载完成
  if (acountList.value.length >= page.value.totalCount) {
    finished.value = true;
  }
};
// 记账逻辑结束

// 删除某一个
// position 为关闭时点击的位置
const beforeClose = ({ position, name }) => {
  console.log(position);
  switch (position) {
    case "outside":
      return true;
    case "right":
      return new Promise((resolve) => {
        showConfirmDialog({
          title: "确定删除吗？",
        })
          .then(async () => {
            console.log(name);
            const { acountType, id, card_id, number } = name;
            const params = {
              acountType,
              id,
              card_id,
              number,
              uid: JSON.parse(localStorage.getItem("userInfo")).id,
            };
            const json = await deleteAccountReq(params);
            if (json.status !== 200) {
              showToast("删除失败，请重试！");
              return resolve(false);
            }
            showToast("删除成功！");
            page.value.pageNum = 1;
            acountList.value = [];
            getData();
            getStatistics();
            return resolve(true);
          })
          .catch(() => resolve(false));
      });
  }
};
const handleExport = () => {
  exportExcel().then((res) => {
    console.log("🚀 ~ handleExport ~ res:", res);
    const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = res.fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  });
};
onMounted(() => {
  computedDate();
  getData();
  getStatistics();
});
</script>
<style scoped lang="scss">
.Accounting {
  .wrapper {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .heard {
    height: 3.0769rem;
    background-color: #3eb575;
    overflow: hidden;

    .title {
      text-align: center;
      margin-top: 0.2563rem;
      color: #fff;
      font-size: 0.4102rem;
    }

    .total {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-template-rows: auto;
      grid-gap: 0.2564rem;
      justify-items: center;
      margin-top: 0.5128rem;

      .totalcount {
        .totaltitle {
          font-size: 0.2564rem;
          color: #fff;
        }

        .number {
          font-size: 0.3077rem;
          font-family: DINPro-Medium, DINPro;
          font-weight: 500;
          color: #ff9424;
        }
      }
    }
    .left {
      display: flex;
      .choose_time {
        margin-top: 0.3846rem;
        margin-left: 0.3846rem;
        color: #fff;
        padding: 0.1282rem;
        background-color: #3eb575;
        font-size: 0.359rem;
        width: 40%;
        border: 0.0256rem solid #fff;
        border-radius: 0.2051rem;

        .time_content {
          margin-left: 0.2051rem;
          margin-right: 0.2051rem;
        }
      }
    }
  }

  .body_list {
    height: calc(100vh - 3.0769rem);
    overflow: hidden;
    overflow-y: scroll;
    background-color: #ededed;
    padding-bottom: 1.2821rem;

    .list_item {
      margin: 0.2051rem;
      background-color: #fff;
      border-radius: 0.2051rem;
      overflow: hidden;

      .item_heard {
        padding: 0.3846rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #fbfbfb;

        .release_time {
          display: flex;
          align-items: center;

          .time_content {
            margin-left: 0.1538rem;
          }
        }

        .income_detail {
          .out {
            .out_content {
            }

            .out_money {
              margin-left: 0.2051rem;
            }
          }

          .in {
            margin-left: 0.2051rem;

            .in_content {
            }

            .in_money {
              margin-left: 0.2051rem;
            }
          }
        }
      }

      .item_content {
        padding: 0.2564rem 0;
        margin: 0 0.3846rem;
        border-bottom: 0.0256rem solid #ededed;

        .name_count {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .name {
          }

          .card_name {
            flex: 1;
            margin-left: 0.2051rem;

            .card_name_content {
              padding: 0 0.0513rem;
            }
          }

          .count {
            color: #c4c2c2;
            padding: 0 0.2564rem 0 0;
          }
        }

        .time_remask {
          color: #c4c2c2;
          margin-top: 0.1538rem;
          display: flex;
          align-items: center;

          .time {
            margin-right: 0.1282rem;
          }

          .remask {
            margin-left: 0.1282rem;
          }
        }
      }
    }
  }
}
</style>
